import { createRouter,createMemoryHistory} from 'vue-router';
import Login from '../view/login/login.vue'
import { ElNotification } from 'element-plus';
import Home from '../view/home/index.vue'
import Show from '../view/Show/index.vue'
import article from '../view/article/index.vue'
import user from '../view/user/index.vue'
import notis from '../view/notis/index.vue'

const router = createRouter({
  history: createMemoryHistory(import.meta.env.BASE_URL),
  routes:[
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'/show',
          component:Show
        },
        {
          path:'/article',
          component:article
        },
        {
          path:'/user',
          component:user
        },
        {
          path:'/notis',
          component:notis
        },
      ]
    }
  ]
    
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const tokenExpiry = localStorage.getItem('tokenExpiry');
  const currentTime = new Date().getTime();
  
  if (token && tokenExpiry && currentTime <= parseInt(tokenExpiry)) {

    // Token 存在且未过期
    if (to.path === '/login' || to.path === '/' ) {
      // 如果已登录，访问登录页时跳转到首页
      ElNotification({
        title: '欢迎回来！',
        message: '您已经登录',
        type: 'success',
        showClose: false,
      });
      next('/show');
    } else {
      next(); // 允许访问目标页面
    }
  } else {
    // Token 不存在或已过期
    if (to.path !== '/login') {
      // 非登录页面，跳转到登录页
      localStorage.removeItem("username")
      localStorage.removeItem("token")
      localStorage.removeItem("tokenExpiry")
      ElNotification({
        title: '登录',
        message: '您还没有登录,请先登录享受所有服务',
        type: 'error',
        showClose: false,
      });
      next('/login');
    } else {
      localStorage.removeItem("username")
      localStorage.removeItem("token")
      localStorage.removeItem("tokenExpiry")
      ElNotification({
        title: '登录',
        message: '您还没有登录,请先登录享受所有服务',
        type: 'error',
        showClose: false,
      });
      next(); // 访问登录页
    }
  }
});

export default router;
